package com.yswl.yeeduo.ui.tool;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.yswl.yeeduo.tool.KLog;
import com.yswl.yeeduo.tool.KSystemTool;

/**
 * 百度获取位置
 * 
 * @author Administrator
 *
 */
public class PositionUtil {

	private Context mContext;

	public PositionUtil(Context context) {
		mContext = context;
		mLocationClient = new LocationClient(context); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener);
		initBD();
	}

	/**
	 * 通过百度API 获取位置经纬度 
	 * 测试key:seir3eEtRphuZY0Tc1YvPAKL
	 * 正式key:FASLBqRvWnPpR2pNFmRV0Iwr
	 */

	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();
	private void initBD() {
		// bdMap-------------------------------------------------------------------------------------------
		mLocationClient = new LocationClient(mContext);// 声明LocationClient类
		mLocationClient.registerLocationListener(myListener);// 注册监听函数
		LocationClientOption option = new LocationClientOption();// 设置请求参数
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
		option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
		// option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);// 返回的定位结果包含地址信息
		option.setNeedDeviceDirect(true);// 返回的定位结果包含手机机头的方向
		mLocationClient.setLocOption(option);
	}

	/**
	 * 启动位置
	 */
	public void startRegin() {
		mLocationClient.start();// 启动请求
		if (mLocationClient != null && mLocationClient.isStarted())
			mLocationClient.requestLocation();
		else
			KLog.e("Location", "locClient is null or not started");
	}

	/**
	 * 停止位置
	 */
	public void stopRegin2() {
		if (mLocationClient.isStarted()) {
			mLocationClient.stop();
		}
	}

	/**
	 * 百度位置监听
	 * 
	 * @author Administrator
	 * 
	 */
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
			}
			KLog.e("test", "=========");
			KLog.e("test", sb.toString());
			// 位置信息保存到application-----------------------------------------------------------------
//			App.latitude = Double.toString(location.getLatitude());
//			App.longitude = Double.toString(location.getLongitude());
			// 位置信息保存到SP------------------------------------------------------------------
			recordPosition(mContext, Double.toString(location.getLatitude()), Double.toString(location.getLongitude()));
			// ----------------------------------------------------------------------------------
			// 得到位置后停止服务
			stopRegin2();
		}

	}

	private void recordPosition(Context context, String latitude, String longitude) {
		SharedPreferences sp = context.getSharedPreferences("position", Activity.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString("latitude", latitude);
		edit.putString("longitude", longitude);
		edit.commit();
	}

	/**
	 * [0] 维度
	 * [1] 经度
	 * @param context
	 * @return
	 */
	public static String[] getSavePosition(Context context) {
		String str[] = new String[2];
//		BDLocation location = new BDLocation();
		SharedPreferences sp = context.getSharedPreferences("position", Activity.MODE_PRIVATE);
//		double la = Double.parseDouble(sp.getString("latitude", ""));
//		double lo = Double.parseDouble(sp.getString("longitude", ""));
//		location.setLatitude(la);
//		location.setLongitude(lo);
		str[0] = sp.getString("latitude", "-1");
		str[1] = sp.getString("longitude", "-1");
		return str;
	}

	/**
	 * <!-- 连接互联网Internet权限 --> <uses-permission
	 * android:name="android.permission.INTERNET" /> <!-- GPS定位权限 -->
	 * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
	 * /> <uses-permission
	 * android:name="android.permission.ACCESS_FINE_LOCATION" />
	 */
	@Deprecated
	public Location getCurrPositionInfo() {
		Location location = null;
		LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

		if (KSystemTool.isNetworkAvailable(mContext)) {
			LocationListener locationListener = new LocationListener() {

				// Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
				@Override
				public void onStatusChanged(String provider, int status, Bundle extras) {
				}

				// Provider被enable时触发此函数，比如GPS被打开
				@Override
				public void onProviderEnabled(String provider) {
				}

				// Provider被disable时触发此函数，比如GPS被关闭
				@Override
				public void onProviderDisabled(String provider) {
				}

				// 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
				@Override
				public void onLocationChanged(Location location) {
					if (location != null) {
						KLog.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
					}
				}
			};
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
			location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

			if (location != null) {
				// latitude = location.getLatitude(); // 纬度
				// longitude = location.getLongitude(); //经度

				KLog.e("POSITION", (String) ("------------维度：" + location.getLatitude() + "  ---------经度：" + location.getLongitude()));
			}
		} else {
			ToastUtil.showShortMsg("请检查网络！");
		}
		return location;
	}

}
